<template>
  <div class="physical-stock">
    <div class="page-header">
      <div class="header-title">
        <h2>库存现有量</h2>
        <el-tag type="info">查看当前库存物料和产品的库存情况</el-tag>
      </div>
    </div>

    <div class="main-content">
      <!-- 左侧树形菜单 -->
      <div class="left-tree">
        <el-card class="tree-card">
          <div class="tree-toolbar">
            <el-input
              v-model="searchForm.classifyName"
              placeholder="请输入分类名称"
              clearable
              @clear="handleTreeSearch"
              @input="handleTreeSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <el-tree
            ref="treeRef"
            :data="filteredTreeData"
            :props="{ label: 'classifyName', children: 'children' }"
            node-key="id"
            highlight-current
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span class="tree-node">
                <el-icon v-if="!data.children || !data.children.length"><Document /></el-icon>
                <el-icon v-else><Folder /></el-icon>
                {{ node.label }}
                <span v-if="data.materialCode" class="material-code">({{ data.materialCode }})</span>
              </span>
            </template>
          </el-tree>
        </el-card>
      </div>

      <!-- 右侧数据表格 -->
      <div class="right-content">
        <el-card class="table-card">
          <div class="search-form">
            <el-form :inline="true" :model="searchForm">
              <el-form-item label="物料编码">
                <el-input 
                  v-model="searchForm.materialCode" 
                  placeholder="请输入物料编码"
                  clearable
                  @keyup.enter="handleSearch"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch">
                  <el-icon><Search /></el-icon>查询
                </el-button>
                <el-button @click="handleReset">
                  <el-icon><Refresh /></el-icon>重置
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-table
            v-loading="loading"
            :data="tableData"
            border
            style="width: 100%"
            :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          >
            <el-table-column prop="materialCode" label="产品物料编码" min-width="120" />
            <el-table-column prop="materialName" label="产品物料名称" min-width="120" />
            <el-table-column prop="specType" label="规格型号" min-width="120" />
            <el-table-column prop="inventoryQuantity" label="在库数量" width="100" align="right" />
            <el-table-column prop="unit" label="单位" width="80" align="center" />
            <el-table-column prop="lotNum" label="批次号" min-width="120" />
            <el-table-column prop="depot" label="仓库名称" min-width="120" />
            <el-table-column prop="galleryArea" label="库区" min-width="120" />
            <el-table-column prop="binLocation" label="库位编码" min-width="120" />
            <el-table-column prop="createTime" label="入库日期" width="180" align="center" />
            <el-table-column label="是否冻结" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="row.status === 1 ? 'danger' : 'success'" effect="plain">
                  {{ row.status === 1 ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="totalItems"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Search,
  Refresh,
  Document,
  Folder
} from '@element-plus/icons-vue'
import http from '@/api/http'

// 树形数据接口
interface TreeNode {
  id: number
  classifyName: string
  materialCode?: string
  children?: TreeNode[]
  parentId?: number
}

// 表格数据接口
interface TableItem {
  id: number
  materialCode: string
  materialName: string
  specType: string
  inventoryQuantity: string
  unit: string
  lotNum: string
  depot: string
  galleryArea: string
  binLocation: string
  createTime: string
  status: number
  parentId: number
}

// 搜索表单接口
interface SearchForm {
  classifyName: string
  materialCode: string
  materialName: string
  batchNumber: string
  warehouseName: string
  locationCode: string
  isFrozen: string
}

// 树形数据
const treeData = ref<TreeNode[]>([])

// 搜索表单数据
const searchForm = ref<SearchForm>({
  classifyName: '',
  materialCode: '',
  materialName: '',
  batchNumber: '',
  warehouseName: '',
  locationCode: '',
  isFrozen: ''
})

// 表格数据
const tableData = ref<TableItem[]>([])

// 当前选中的分类ID
const currentClassifyId = ref<number | null>(null)

// 本地过滤和分页
const localFilterAndPaginate = (data: TableItem[]) => {
  let result = [...data]
  
  // 应用搜索条件
  if (searchForm.value.materialCode) {
    result = result.filter(item => 
      item.materialCode.toLowerCase().includes(searchForm.value.materialCode.toLowerCase())
    )
  }
  if (searchForm.value.materialName) {
    result = result.filter(item => 
      item.materialName.toLowerCase().includes(searchForm.value.materialName.toLowerCase())
    )
  }
  if (searchForm.value.batchNumber) {
    result = result.filter(item => 
      item.lotNum.toLowerCase().includes(searchForm.value.batchNumber.toLowerCase())
    )
  }
  if (searchForm.value.warehouseName) {
    result = result.filter(item => 
      item.depot.toLowerCase().includes(searchForm.value.warehouseName.toLowerCase())
    )
  }
  if (searchForm.value.locationCode) {
    result = result.filter(item => 
      item.binLocation.toLowerCase().includes(searchForm.value.locationCode.toLowerCase())
    )
  }
  if (searchForm.value.isFrozen !== '') {
    result = result.filter(item => 
      item.status === parseInt(searchForm.value.isFrozen)
    )
  }

  // 计算总数
  totalItems.value = result.length
  
  // 分页
  const startIndex = (currentPage.value - 1) * pageSize.value
  return result.slice(startIndex, startIndex + pageSize.value)
}

// 获取表格数据
const getTableData = async () => {
  try {
    loading.value = true
    let url = '/api/Warehouses/GetPhysicalStockList'
    if (searchForm.value.materialCode) {
      url += '?materialCode=' + encodeURIComponent(searchForm.value.materialCode)
    }
    
    console.log('请求URL:', url)
    const response = await http.get(url)
    console.log('获取到的数据:', response)
    
    if (response && response.data) {
      tableData.value = response.data
      totalItems.value = response.total || 0
      console.log('更新后的表格数据:', tableData.value)
    } else {
      console.warn('返回数据格式不正确:', response)
      ElMessage.error('获取库存数据失败')
      tableData.value = []
      totalItems.value = 0
    }
  } catch (error: any) {
    console.error('获取库存数据失败:', error)
    ElMessage.error('获取库存数据失败：' + error.message)
    tableData.value = []
    totalItems.value = 0
  } finally {
    loading.value = false
  }
}

// 获取树形数据
const getTreeData = async () => {
  try {
    loading.value = true
    console.log('开始获取树形数据')
    const response = await http.get('/api/Warehouses/GetTree')
    console.log('树形数据响应:', response)
    
    if (response && response.data) {
      treeData.value = response.data
      console.log('设置树形数据:', treeData.value)
    } else {
      console.warn('返回树形数据格式不正确:', response)
      ElMessage.error('获取分类数据失败')
      treeData.value = []
    }
  } catch (error: any) {
    console.error('获取分类数据失败:', error)
    ElMessage.error('获取分类数据失败：' + error.message)
    treeData.value = []
  } finally {
    loading.value = false
  }
}

// 树形搜索过滤
const filteredTreeData = computed(() => {
  console.log('过滤前的树形数据:', treeData.value)
  if (!searchForm.value.classifyName) return treeData.value
  
  const search = searchForm.value.classifyName.toLowerCase()
  const filterTree = (nodes: TreeNode[]): TreeNode[] => {
    return nodes.filter(node => {
      const matches = node.classifyName.toLowerCase().includes(search)
      
      if (node.children && node.children.length) {
        const filteredChildren = filterTree(node.children)
        if (filteredChildren.length) {
          return {
            ...node,
            children: filteredChildren
          }
        }
      }
      
      return matches
    })
  }
  
  const filtered = filterTree([...treeData.value])
  console.log('过滤后的树形数据:', filtered)
  return filtered
})

// 表格搜索和分页
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(0)

const filteredTableData = ref<TableItem[]>([])

// 事件处理
const handleTreeSearch = () => {
  // 树形搜索逻辑已通过计算属性实现
}

// 树节点点击事件
const handleNodeClick = (data: any) => {
  console.log('点击的节点数据:', data)
  // 如果节点有 materialCode，直接查询
  if (data.materialCode) {
    console.log('找到物料编码:', data.materialCode)
    searchForm.value.materialCode = data.materialCode
    getTableData()
    return
  }
  
  // 如果是父节点，获取所有子节点的 materialCode
  const getAllChildrenMaterialCodes = (node: any): string[] => {
    let codes: string[] = []
    if (node.materialCode) {
      codes.push(node.materialCode)
    }
    if (node.children && node.children.length > 0) {
      node.children.forEach((child: any) => {
        codes = codes.concat(getAllChildrenMaterialCodes(child))
      })
    }
    return codes
  }

  const materialCodes = getAllChildrenMaterialCodes(data)
  console.log('获取到的所有物料编码:', materialCodes)

  if (materialCodes.length > 0) {
    // 使用第一个物料编码进行查询
    searchForm.value.materialCode = materialCodes[0]
    console.log('使用第一个物料编码查询:', materialCodes[0])
    getTableData()
  } else {
    console.log('未找到物料编码，清空表格数据')
    // 如果没有物料编码，清空表格数据
    tableData.value = []
    totalItems.value = 0
  }
}

// 搜索处理
const handleSearch = () => {
  getTableData()
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    classifyName: '',
    materialCode: '',
    materialName: '',
    batchNumber: '',
    warehouseName: '',
    locationCode: '',
    isFrozen: ''
  }
  getTableData()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getTableData()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getTableData()
}

// 添加加载状态
const loading = ref(false)

// 修改初始化加载
onMounted(async () => {
  try {
    loading.value = true
    console.log('组件挂载，开始加载数据')
    await getTreeData()
    await getTableData()
    console.log('初始化数据加载完成')
  } catch (error) {
    console.error('初始化加载失败:', error)
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.physical-stock {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-title h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.main-content {
  display: flex;
  gap: 20px;
  height: calc(100vh - 180px);
}

.left-tree {
  width: 280px;
  flex-shrink: 0;
}

.tree-card {
  height: 100%;
}

.tree-toolbar {
  margin-bottom: 16px;
}

.right-content {
  flex: 1;
  min-width: 0;
}

.table-card {
  height: 100%;
}

.search-form {
  margin-bottom: 16px;
  
  :deep(.el-form--inline .el-form-item) {
    margin-bottom: 16px;
  }

  :deep(.el-form-item__label) {
    font-weight: normal;
    color: #606266;
  }
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 4px;
}

.material-code {
  color: #909399;
  font-size: 12px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-card__body) {
  height: calc(100% - 20px);
  display: flex;
  flex-direction: column;
}

:deep(.el-tree) {
  flex: 1;
  overflow: auto;
}

:deep(.el-table) {
  flex: 1;
  overflow: auto;
}
</style>